﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="EndpointBase.cs" company="Jim Liddell">
//   Copyright © Jim Liddell. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace TeamBuildBunny
{
    #region Usings

    using System.IO;
    using System.Xml;
    using System.Xml.Serialization;

    using Properties;

    #endregion

    /// <summary>
    /// Provides common functionality for an endpoint.
    /// </summary>
    public abstract class EndpointBase
    {
        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="EndpointBase"/> class.
        /// </summary>
        protected EndpointBase()
        {
            this.Bunnies = Settings.Default.Bunnies;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets the <see cref="NabaztagCollection"/>.
        /// </summary>
        protected NabaztagCollection Bunnies
        {
            get; private set;
        }

        #endregion

        #region Methods

        /// <summary>
        /// Deserializes an object from the specified XML.
        /// </summary>
        /// <typeparam name="T">
        /// The type to deserialize as.
        /// </typeparam>
        /// <param name="serializedType">
        /// The XML representation of the type.
        /// </param>
        /// <returns>
        /// An object deserialized from the specified XML.
        /// </returns>
        protected T CreateInstance<T>(string serializedType) where T : new()
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            StringReader stream = new StringReader(serializedType);
            XmlReader xmlReader = new XmlTextReader(stream);

            return (T)serializer.Deserialize(xmlReader);
        }

        /// <summary>
        /// Returns the username from the specified <see cref="string"/>.
        /// </summary>
        /// <param name="s">The <see cref="string"/>.</param>
        /// <returns>If <paramref name="s"/> contains a '\' character, then everything after will be returned, otherwise the original string is returned.</returns>
        protected string GetUserName(string s)
        {
            return s.Contains("\\") ? s.Split('\\')[1] : s;
        }

        #endregion
    }
}